<?php

/**
 * ECSHOP mobile首页
 * ============================================================================
 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liuhui $
 * $Id: index.php 15013 2010-03-25 09:31:42Z liuhui $
*/

define('IN_ECS', true);
define('ECS_ADMIN', true);

require(dirname(__FILE__) . '/includes/init.php');
require(dirname(__FILE__) . '/includes/lib_index.php');
require(dirname(__FILE__) . '/includes/auto_login.php');
require(dirname(__FILE__) . '/includes/wx_option.php');
require(dirname(__FILE__) . '/includes/phpqrcode.php');

$act = !empty($_REQUEST['act'])? $_REQUEST['act'] : '';
/*用户数据*/
$user_info = $GLOBALS['db']->getRow('SELECT * FROM '.$GLOBALS['ecs']->table('users').' WHERE wecha_id = "'.$_SESSION['openids'].'"');
if ($user_info) {
    $_SESSION['user_id'] = $user_info['user_id'];
    $smarty->assign('user_info',$user_info);
}

//选择自动定位
if ($act == 'autopos') {
    $_SESSION['city_id'] = $_SESSION['pos_city_id'];
    $_SESSION['district'] = "选择地区";
}


/*位置*/
if ($_SESSION['city_id']) {
   $city = $GLOBALS['db']->getOne('SELECT region_name FROM '.$GLOBALS['ecs']->table('region').' WHERE region_id = "'.$_SESSION['city_id'].'"');
    $smarty->assign('city',$city);
    $smarty->assign('city_id',$_SESSION['city_id']);
}
if (!empty($_SESSION['district'])) {
    $smarty->assign('district',$_SESSION['district']);
}

//定位ajax
if ($act == 'setpos') {
    
    $lat = $_POST['lat'];
    $lng = $_POST['lng'];
    $city = $_POST['pos'];
    $result = array(
            "err"=>1,
            "city_name"=>'',
        );

    if (!empty($lat) && !$_SESSION['pos_city_id']) {
        $_SESSION['lat'] = $lat; 
        $_SESSION['lng'] = $lng;
        $city =  js_unescape($city);
        
        $city_name = str_replace("市","",$city);
        $city_id = $GLOBALS['db']->getOne('SELECT region_id FROM '.$GLOBALS['ecs']->table('region').' WHERE region_name like "%'.$city_name.'%"');
        $_SESSION['city_id'] = $city_id;
        $_SESSION['pos_city_id'] = $city_id;

        $result['city_name'] = $city_name;
        
        $result['err'] = 0;
    }

    $result = json_encode($result);
    die($result);exit;
}

//查找结果静态 
if ($act == 'search_res') {
    $smarty->display('search_res.dwt');exit;
}

//用户信息
if ($act == 'user_profile') {
    $smarty->assign('user_profile',1);
    $sub_count = $GLOBALS['db']->getOne('SELECT COUNT(*) FROM '.$GLOBALS['ecs']->table('users').' WHERE parent_id = "'.$user_info['user_id'].'"');
    $smarty->assign('sub_count',$sub_count);
    //服务员数据
    if ($user_info['is_waiter'] == 1) {
        $sale_log = $GLOBALS['db']->getOne('SELECT COUNT(*) FROM '.$GLOBALS['ecs']->table('sales_log').' WHERE waiter_id = "'.$user_info['user_id'].'"');
        $smarty->assign('log_count',$sale_log);
    }
    //区域代理数据
    if ($user_info['is_delegate'] == 1) {
        $sub_shop_count = $GLOBALS['db']->getOne('SELECT COUNT(*) FROM '.$GLOBALS['ecs']->table('goods').' WHERE district = "'.$user_info['district'].'"');
        $sub_member = $GLOBALS['db']->getOne('SELECT COUNT(*) FROM '.$GLOBALS['ecs']->table('users').' WHERE district = "'.$user_info['district'].'" AND user_id <> "'.$user_info['user_id'].'"');
        $smarty->assign('sub_shop_count',$sub_shop_count);
        $smarty->assign('sub_member_count',$sub_member);
    }
    //佣金记录
    $commission_count = $GLOBALS['db']->getOne('SELECT COUNT(*) FROM '.$GLOBALS['ecs']->table('commission_log').' WHERE user_id = "'.$user_info['user_id'].'"');
    $smarty->assign('user_id',$user_info['user_id']);
    $smarty->assign('com_count',$commission_count);
    $smarty->display('user_profile.dwt');exit;
}
/*店员的销售记录*/
elseif ($act == 'waiter_log') {
    $smarty->assign('waiter_log',1);
    $sale_detail = $GLOBALS['db']->getAll('SELECT * FROM '.$GLOBALS['ecs']->table('sales_log').' WHERE waiter_id = "'.$user_info['user_id'].'"');
    foreach ($sale_detail as $k => $v) {
       $sale_detail[$k]['date_format'] =  date('Y-m-d',$v['add_time']);
       $sale_detail[$k]['user_name'] = $GLOBALS['db']->getOne('SELECT user_name FROM '.$GLOBALS['ecs']->table('users').' WHERE user_id = '.$v['user_id']); 
    }
    $smarty->assign('waiter_log',$sale_detail);
    $smarty->display('user_profile.dwt');exit;
}

elseif ($act == 'rand_bonus') {
    $smarty->display('rand_bonus.dwt');exit;
}

/*店员收款二维码:商店的*/
elseif ($act == 'shop_qrcode') {
    $errorCorrectionLevel = 'L';//容错级别  
    $matrixPointSize = 6;//生成图片大小
    $shop_id = $GLOBALS['db']->getOne("SELECT from_shop FROM ".$GLOBALS['ecs']->table("users")." WHERE user_id = '$_SESSION[user_id]'"); 
    $data = 'http://ytt2.tophp.cn/mobile/pay.php?act=pay&shop='.$shop_id;
    //生成二维码图片  
    QRcode::png($data, 'qrcode.png', $errorCorrectionLevel, $matrixPointSize, 2);
    $smarty->display('shop_qrcode.dwt');exit;
}

//区域代理下属会员
elseif ($act == 'sub_member') {
    $member_list = $GLOBALS['db']->getAll('SELECT user_name, reg_time FROM '.$GLOBALS['ecs']->table('users').' WHERE district = "'.$user_info['district'].'" AND user_id <> "'.$user_info['user_id'].'"');
    if (count($member_list) > 0) {
        foreach ($member_list as $k => $v) {
            $member_list[$k]['reg_time_format'] = date('Y-m-d',$v['reg_time']);
        }
    }
    $smarty->assign('sub_member',1);
    $smarty->assign('member_list',$member_list);
    $smarty->display('user_profile.dwt');exit;
}

//区域代理下属商家
elseif ($act == 'sub_shop') {
    $shop_list = $GLOBALS['db']->getAll('SELECT * FROM '.$GLOBALS['ecs']->table('goods').' WHERE district = "'.$user_info['district'].'"');
    if (count($shop_list) > 0) {        
        foreach ($shop_list as $k => $v) {
            $shop_list[$k]['reg_time_format'] = date('Y-m-d',$v['add_time']);
        }
        $smarty->assign('shop_list',$shop_list);
    }
    $smarty->assign('sub_shop',1);
    $smarty->display('user_profile.dwt');exit;
}

//佣金记录
elseif ($act == 'commission_log') {
    $smarty->assign('commission_log',1);
    $commission_list = $GLOBALS['db']->getAll('SELECT * FROM '.$GLOBALS['ecs']->table('commission_log').' WHERE user_id = "'.$user_info['user_id'].'"');
    if (count($commission_list) > 0 ) {
        foreach ($commission_list as $k => $v) {
            $commission_list[$k]['reg_time_format'] = date('Y-m-d',$v['add_time']);
        }
        $smarty->assign('commission_list',$commission_list);
    }
    $smarty->display('user_profile.dwt');exit;
}

//商家登录静态 
elseif ($act == 'shop_login') {
    $smarty->display('shop_login.dwt');exit;
}
//城市切换静态 
elseif ($act == 'sel_city') {
    $smarty->display('sel_city.dwt');exit;
}
//商家申请静态 
elseif ($act == 'shop_reg') {
    $smarty->display('shop_reg.dwt');exit;
}
//推广二维码静态 
elseif ($act == 'extension') {
    //参数为场景码
    $rec_id = $user_info['user_id'];
    $qr_img = get_qr_img($rec_id);
    $smarty->assign('qr_img',$qr_img);
    $smarty->display('extension.dwt');exit;
}//我的粉丝静态 
elseif ($act == 'my_fans') {
    $smarty->display('my_fans.dwt');exit;
}//我要赚钱静态 
elseif ($act == 'earn_money') {
    //参数为场景码
    $rec_id = $user_info['user_id'];
    $qr_img = get_qr_img($rec_id);
    $smarty->assign('qr_img',$qr_img);
    $smarty->display('earn_money.dwt');exit;
}//商店详情静态
elseif ($act == 'shop_detail') {
    $smarty->display('shop_detail.dwt');exit;
}
/*用户的消费明细*/
elseif ($act == 'sale_detail') {
    $sale_detail = $GLOBALS['db']->getAll('SELECT * FROM '.$GLOBALS['ecs']->table('sales_log').' WHERE user_id = "'.$user_info['user_id'].'"');
    foreach ($sale_detail as $k => $v) {
       $sale_detail[$k]['date_format'] =  date('Y-m-d',$v['add_time']);
       $sale_detail[$k]['shop_name'] = $GLOBALS['db']->getOne('SELECT goods_name FROM '.$GLOBALS['ecs']->table('goods').' WHERE goods_id = "'.$v['shop_id'].'"');
    }

    $smarty->assign('sale_details',$sale_detail);
    $smarty->assign('sale_detail',1);
    $smarty->assign('user_id',$user_info['user_id']);
    $smarty->display('user_profile.dwt');exit;
}

/*用户推荐下线*/
elseif ($act == 'rec_list') {
    $smarty->assign('rec_list',1);
    $sub_user_list = $GLOBALS['db']->getAll('SELECT * FROM '.$GLOBALS['ecs']->table('users').' WHERE parent_id = "'.$user_info['user_id'].'"');
    foreach ($sub_user_list as $k => $v) {
        $sub_user_list[$k]['reg_time_format'] = date('Y-m-d',$sub_user_list[$k]['reg_time']);
    }
    $smarty->assign('sub_list',$sub_user_list);
    $smarty->assign('user_id',$user_info['user_id']);
    $smarty->display('user_profile.dwt');exit;
}

/*用户提现界面*/
elseif ($act == 'get_cash') {
    $smarty->assign('get_cash',1);
    $smarty->display('user_profile.dwt');exit;
}
/*提现操作*/
elseif ($act == 'act_get_cash') {
    //检查用户余额及提现余额
    $money = $_POST['domoney'];
    $user_ye = $user_info['user_money'];
    if ($user_ye < $money) {
        send_err_msg('您的余额不足，无法提现');
    }
    if ($money < 0) {
        send_err_msg('输入的金额不合法');
    }
    //提现流程: 1.记录到user_account 2.记录到account_log 3.更新users表中的用户余额
    $user_id = $user_info['user_id'];
    $amount = -1 * $money;
    $add_time = time();
    $add_time -= 28800;
    $admin_note = '申请通过';
    $user_note = '提现申请';
    $process_type = 1;
    $is_paid = 0;

    $GLOBALS['db']->query('INSERT INTO '.$GLOBALS['ecs']->table('user_account').' ( user_id, amount, add_time, paid_time, admin_note, user_note, process_type, is_paid ) VALUES ( "'.$user_id.'", "'.$amount.'", "'.$add_time.'", "'.$add_time.'", "'.$admin_note.'", "'.$user_note.'", "'.$process_type.'", "'.$is_paid.'" )');
    $frozen_money = 0;      
    $rank_points = 0;
    $pay_points = 0;
    $change_desc = '提现';
    $change_type = 1;

    $GLOBALS['db']->query('INSERT INTO '.$GLOBALS['ecs']->table('account_log').' ( user_id, user_money, frozen_money, rank_points, pay_points, change_time, change_desc, change_type )  VALUES( "'.$user_id.'", "'.$amount.'", "'.$frozen_money.'", "'.$rank_points.'", "'.$pay_points.'", "'.$add_time.'", "'.$change_desc.'", "'.$change_type.'" ) ');

    $GLOBALS['db']->query('UPDATE '.$GLOBALS['ecs']->table('users').'SET user_money = user_money - '.$money.' WHERE user_id = "'.$user_info['user_id'].'"');
    
    //微信自动发红包
    //
    //
    //
    //

    show_yj_message($content='操作成功', $href = 'index.php', $type = 'success');
}

/*成为商家的上家*/
elseif ($act == 'action_earn') {
    //数据获取
    $shop_name = isset($_POST['shop_name']) ? $_POST['shop_name'] : '';
    $shop_addr = isset($_POST['shop_addr']) ? $_POST['shop_addr'] : '';
    $boss_name = isset($_POST['boss_name']) ? $_POST['boss_name'] : '';
    $boss_tel = isset($_POST['boss_tel']) ? $_POST['boss_tel'] : '';

    $goods_info = $GLOBALS['db']->getRow('SELECT * FROM '.$GLOBALS['ecs']->table('goods').' WHERE goods_name like "%'.$shop_name.'%"');
    if ($goods_info) {
        $true_boss = $GLOBALS['db']->getRow('SELECT * FROM '.$GLOBALS['ecs']->table('users').' WHERE user_id = "'.$goods_info['user_id'].'"');
        if ($true_boss['user_name'] == $boss_name && $true_boss['tel'] == $boss_tel && $shop_addr == $goods_info['address']) {
            /*添加为商家推荐人*/
            $GLOBALS['db']->query(' UPDATE '.$GLOBALS['ecs']->table('goods').' SET rec_id = "'.$user_info['user_id'].'"');
            show_yj_message('操作成功', $href = 'index.php', $type = 'success');
        }
    }
    /*提示失败*/
    send_err_msg('不存在的商家');
}

/* 最新商品 */
$new_goods = get_recommend_goods_wap('new',6);
$new_goods = sort_by_distance($new_goods);
$new_num = count($new_goods);
$smarty->assign('new_num' , $new_num);
$smarty->assign('new_goods' , $new_goods);

/* 推荐商品 */
$best_goods = get_recommend_goods_wap('best',6);
$best_goods = sort_by_distance($best_goods);
$best_num = count($best_goods);
$smarty->assign('best_num' , $best_num);
$smarty->assign('best_goods' , $best_goods);

/* 热门商品 */
$hot_goods = get_recommend_goods_wap('hot',6);
$hot_goods = sort_by_distance($hot_goods);
$hot_num = count($hot_goods);
$smarty->assign('hot_num' , $hot_num);
$smarty->assign('hot_goods' , $hot_goods);


/* 促销商品 */
$promote_goods = get_promote_goods_wap();
$promote_num = count($promote_goods);
$smarty->assign('promote_num' , $promote_num);
if ($promote_num > 0)
{
    //$i = 0;
    // foreach ($promote_goods as $key => $promote_data)
    // {
    //     $promote_goods[$key]['shop_price'] = encode_output($promote_data['shop_price']);
    //     $promote_goods[$key]['name'] = encode_output($promote_data['name']);
    //     $i++;
    // }
    $smarty->assign('promote_goods' , $promote_goods);
}

$pcat_array = get_categories_tree();
foreach ($pcat_array as $key => $pcat_data)
{
	$pcat_array[$key]['name'] = encode_output($pcat_data['name']);
	if ($pcat_data['cat_id'])
	{
		if (count($pcat_data['cat_id']) > 3)
		{
			$pcat_array[$key]['cat_id'] = array_slice($pcat_data['cat_id'], 0, 3);
		}
		foreach ($pcat_array[$key]['cat_id'] as $k => $v)
		{
			$pcat_array[$key]['cat_id'][$k]['name'] = encode_output($v['name']);
		}
	}
}
$smarty->assign('pcat_array' , $pcat_array);
$brands_array = get_brands();
if (!empty($brands_array))
{
	if (count($brands_array) > 3)
	{
		$brands_array = array_slice($brands_array, 0, 10);
	}
	foreach ($brands_array as $key => $brands_data)
	{
		$brands_array[$key]['brand_name'] = encode_output($brands_data['brand_name']);
	}
	$smarty->assign('brand_array', $brands_array);
}

$article_array = $db->GetALLCached("SELECT article_id, title FROM " . $ecs->table("article") . " WHERE cat_id != 0 AND is_open = 1 AND open_type = 0 ORDER BY article_id DESC LIMIT 0,4");

if (!empty($article_array))
{
	foreach ($article_array as $key => $article_data)
	{
		$article_array[$key]['title'] = encode_output($article_data['title']);
	}
	$smarty->assign('article_array', $article_array);
}
if ($_SESSION['user_id'] > 0)
{
	$smarty->assign('user_name', $_SESSION['user_name']);
}

if (!empty($GLOBALS['_CFG']['search_keywords']))
{
	$searchkeywords = explode(',', trim($GLOBALS['_CFG']['search_keywords']));
}
else
{
	$searchkeywords = array();
}
//轮播图广告
$main_ads = get_cyc_ad();
$smarty->assign('main_ads',$main_ads);

$yj_cate = $GLOBALS['db']->getAll('SELECT * FROM '.$GLOBALS['ecs']->table('category').' WHERE 1');
$smarty->assign('yj_cate',$yj_cate);
$smarty->assign('searchkeywords', $searchkeywords);
$smarty->assign('wap_logo', $_CFG['wap_logo']);
$smarty->assign('footer', get_footer());

if ($_REQUEST['city'] != '') {
    $city = $GLOBALS['db']->getOne('SELECT region_name FROM '.$GLOBALS['ecs']->table('region').' WHERE region_id = "'.$_REQUEST['city'].'"');
    $_SESSION['city_id'] = $_REQUEST['city'];
    $_SESSION['district'] = "选择地区";
    $smarty->assign('district',$_SESSION['district']);
    $smarty->assign('city_id',$_SESSION['city_id']);
    $smarty->assign('city',$city);
}

if ( $act == 'dis' && $_REQUEST['district'] != '') {
    $district = $GLOBALS['db']->getOne('SELECT region_name FROM '.$GLOBALS['ecs']->table('region').' WHERE region_id = "'.$_REQUEST['district'].'"');
    $_SESSION['dis_id'] = $_REQUEST['district'];
    $_SESSION['district'] = $district;
    $smarty->assign('district',$district);
}

$smarty->display("index_static.dwt");



/**
 * 获得文章分类下的文章列表
 *
 * @access  public
 * @param   integer     $cat_id
 * @param   integer     $page
 * @param   integer     $size
 *
 * @return  array
 */
function get_cat_articles($cat_id, $page = 1, $size = 20 ,$requirement='')
{
    //取出所有非0的文章
    if ($cat_id == '-1')
    {
        $cat_str = 'cat_id > 0';
    }
    else
    {
        $cat_str = get_article_children($cat_id);
    }
    //增加搜索条件，如果有搜索内容就进行搜索    
    if ($requirement != '')
    {
        $sql = 'SELECT article_id, title, author, add_time, file_url, open_type' .
               ' FROM ' .$GLOBALS['ecs']->table('article') .
               ' WHERE is_open = 1 AND title like \'%' . $requirement . '%\' ' .
               ' ORDER BY article_type DESC, article_id DESC';
    }
    else 
    {
        
        $sql = 'SELECT article_id, title, author, add_time, file_url, open_type' .
               ' FROM ' .$GLOBALS['ecs']->table('article') .
               ' WHERE is_open = 1 AND ' . $cat_str .
               ' ORDER BY article_type DESC, article_id DESC';
    }

    $res = $GLOBALS['db']->selectLimit($sql, $size, ($page-1) * $size);

    $arr = array();
    if ($res)
    {
        while ($row = $GLOBALS['db']->fetchRow($res))
        {
            $article_id = $row['article_id'];

            $arr[$article_id]['id']          = $article_id;
            $arr[$article_id]['title']       = $row['title'];
            $arr[$article_id]['short_title'] = $GLOBALS['_CFG']['article_title_length'] > 0 ? sub_str($row['title'], $GLOBALS['_CFG']['article_title_length']) : $row['title'];
            $arr[$article_id]['author']      = empty($row['author']) || $row['author'] == '_SHOPHELP' ? $GLOBALS['_CFG']['shop_name'] : $row['author'];
            $arr[$article_id]['url']         = $row['open_type'] != 1 ? build_uri('article', array('aid'=>$article_id), $row['title']) : trim($row['file_url']);
            $arr[$article_id]['add_time']    = date($GLOBALS['_CFG']['date_format'], $row['add_time']);
        }
    }

    return $arr;
}

/**
 * 腾讯定位数据转中文
 * @param  [type] $str [description]
 * @return [type]      [description]
 */
function js_unescape($str)  
{  
    $ret = '';  
    $len = strlen($str);  
    for ($i = 0; $i < $len; $i++) {  
        if ($str[$i] == '%' && $str[$i+1] == 'u') {  
            $val = hexdec(substr($str, $i+2, 4));  
            if ($val < 0x7f) $ret .= chr($val);  
            else if($val < 0x800) $ret .= chr(0xc0|($val>>6)).chr(0x80|($val&0x3f));  
            else $ret .= chr(0xe0|($val>>12)).chr(0x80|(($val>>6)&0x3f)).chr(0x80|($val&0x3f));  
            $i += 5; 
        } else if ($str[$i] == '%') {  
            $ret .= urldecode(substr($str, $i, 3));  
            $i += 2;      
        } else $ret .= $str[$i];  
    }  
    return $ret;  
}

/**
 * 距离排序
 * @param  array $array  源数组
 * @return array        目标数组
 */
function sort_by_distance($array)
{
    //按距离排序
    if ($_SESSION['lat'] && $_SESSION['lng']) 
    {
        $sort = array(  
        'direction' => 'SORT_ASC', //排序顺序标志 SORT_DESC 降序；SORT_ASC 升序  
        'field'     => 'distance',       //排序字段  
        );  
        $arrSort = array();  
        foreach($array AS $uniqid => $row){  
            foreach($row AS $key=>$value){  
                $arrSort[$key][$uniqid] = $value;  
            }  
        }  
        if($sort['direction']){  
            array_multisort($arrSort[$sort['field']], constant($sort['direction']), $array);  
        } 
    }
    return $array;
} 
?>
